from django.shortcuts import render
from django.shortcuts import HttpResponse
from django.http import JsonResponse
import json
import sys
from api import functions
functions_module = sys.modules[functions.__name__]

def cros(data):
    response = HttpResponse(json.dumps(data), content_type='application/json')
    # response['Access-Control-Allow-Origin'] = '*'
    # response['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
    # response['Access-Control-Max-Age'] = '1000'
    # response['Access-Control-Allow-Headers'] = 'Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild'
    return response
def api(request):
    # 初始化一个字典作为返回值
    data = {'code': None,'msg': None,'result': None}
    # request['Access-Control-Allow-Origin'] = "*"
    #如果请求方法是get
    print(request.POST)
    if request.method == 'GET':
        #接受get请求来的参数
        fun = request.GET.get('fun')
        if fun!= None:
        #如果functions文件中有变量fun这个函数  post方法同理
            if hasattr(functions_module,fun):
                data = getattr(functions_module, fun)(request)
        else:
            data["result"] = '非法提交'
            response = HttpResponse(json.dumps(data), content_type='application/json')
            response['Access-Control-Allow-Origin'] = '*'
            response['Access-Control-Allow-Methods'] = 'POST,GET,OPTIONS'
            response['Access-Control-Max-Age'] = '1000'
            response['Access-Control-Allow-Headers'] = '*'
            return response
    #请求方法是post
    elif request.method == 'POST':
        fun = request.POST.get('fun')
        if fun!= None:
            if hasattr(functions_module, fun):
                data = getattr(functions_module, fun)(request)
                # response = cros(data)
                return JsonResponse(data)
        else:
            data["result"] = '非法提交'
            # response = HttpResponse(json.dumps(data), content_type='application/json')
            response = cros(data)

            return response
    elif request.method == 'OPTIONS':
        response = cros(data)
        return response
    else:
        response = cros(data)
        return response
    # return JsonResponse(data)
    response = cros(data)
    return response
def index(request):

    return HttpResponse('这是首页')